import Axios, { type AxiosInstance, type AxiosError, type AxiosResponse, type AxiosRequestConfig } from 'axios';
// import { ResultEnum } from "@/enums/request-enum"; // ContentTypeEnum,
import NProgress from '../progress';
import { showFailToast } from 'vant';
import 'vant/es/toast/style';
import { useUserStore } from '@/store/modules/user-info';
import { useMultiAccountStore } from '@/store/modules/multi-account';
import { useRouter } from 'vue-router';

// 默认 axios 实例请求配置
const configDefault = {
  timeout: 0,
  baseURL: 'admin',
  data: {},
};

class Http {
  // 当前实例
  private static axiosInstance: AxiosInstance;
  // 请求配置
  private static axiosConfigDefault: AxiosRequestConfig;

  // 请求拦截
  private httpInterceptorsRequest(): void {
    Http.axiosInstance.interceptors.request.use(
      (config) => {
        NProgress.start();
        const userStore = useUserStore();
        config.headers['accept-language'] = userStore.i18nLocale;

        // 发送请求前，可在此携带 token
        if (userStore.accessToken) {
          config.headers['we-services-token'] = userStore.accessToken;
        }
        return config;
      },
      (error: AxiosError) => {
        showFailToast(error.message);
        return Promise.reject(error);
      }
    );
  }

  // 响应拦截
  private httpInterceptorsResponse(): void {
    Http.axiosInstance.interceptors.response.use(
      (response: AxiosResponse) => {
        NProgress.done();
        // 与后端协定的返回字段
        const { code } = response.data;
        // const { message } = response.data;
        // 判断请求是否成功
        const isSuccess = code === 0;
        // result &&
        // Reflect.has(response.data, "code") &&
        // code === ResultEnum.SUCCESS;
        if (isSuccess) {
          return response.data;
        } else {
          // 处理请求错误
          // showFailToast(message);
          return Promise.reject(response.data);
        }
      },
      (error: AxiosError) => {
        NProgress.done();
        const status = error.response?.status;

        showFailToast((error.response.data as { msg: string }).msg || '服务器无响应');
        // 跳转登录
        if (status === 401) {
          const router = useRouter(); // 获取路由实例
          const userStore = useUserStore();
          const multiAccountStore = useMultiAccountStore();
          multiAccountStore.removeAccount(userStore.userInfo.userId);
          userStore.clearLock();
          // router.replace({ name: 'login' }); // 或者 path: '/login'
          window.location.href = '/login'; // 临时替代 router
        }

        return Promise.reject(error);
      }
    );
  }

  constructor(config: AxiosRequestConfig) {
    Http.axiosConfigDefault = config;
    Http.axiosInstance = Axios.create(config);
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }

  // 通用请求函数
  public request<T>(paramConfig: AxiosRequestConfig): Promise<T> {
    const config = { ...Http.axiosConfigDefault, ...paramConfig };
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
}

export const http = new Http(configDefault);
